<template>
  <view>
    <scroll-view scroll-y style="height: 100vh">
      <view v-if="isLogin"
            :style="{backgroundImage: 'url(' + userInfo.backgroundUrl + ')'}"
            @tap="toAlterBackgroud(userInfo.backgroundUrl)"
            class="container">
        <view>
          <view class="userinfo" :style="{height: bgHeight }">
            <view class="avatar">
              <image @tap.stop="toAlterAvatar(userInfo.avatar)" :src="userInfo.avatar"></image>
            </view>
            <navigator class="name" :url="`/pages/my/info?userId=${userId}`">
              <text>{{ userInfo.username }}</text>
            </navigator>
          </view>
        </view>
        <view class="top-right-list" @tap.stop="ShowRightList()">
          <u-icon color="#fff" size="28" name="list"></u-icon>
        </view>
        <view>
          <u-popup :safeAreaInsetBottom="false"
                   :overlayOpacity="0"
                   safeAreaInsetTop mode="right" :show="showRightList"
                   @tap.stop
                   @close.stop="close" @open="open">
            <view class="list-wrapper">

              <view class="list-item-out" @click="logout()">
                <image style="width: 20px;height: 20px;"
                       src="https://www.douluodalu.icu:9000/school/static/logout.png"></image>
                &nbsp;&nbsp;&nbsp;<text>退出登录</text>
              </view>
              <view style="margin: 10px 0;height: 10px;">
                <u-line></u-line>
              </view>
            </view>

          </u-popup>
        </view>
      </view>
      <navigator v-else class="userinfo_unlogin" url="/pages/my/login">
        <image style="width: 9.5rem;height: 12rem;" src="https://www.douluodalu.icu:9000/school/campus.png"></image>
        <text class="unlogin_text">立即登录</text>
      </navigator>
      <!--    登录-->
      <view v-if="isLogin" class="content">
        <navigator :url="`/pages/my/info?userId=${userId}`" class="info">
          <view class="relation">
            <view>
              <text class="relation-number">{{ checkParam(userInfo.likes) }}</text>
              <text class="relation-item">&nbsp;获赞</text>
            </view>&nbsp;&nbsp;
            <view>
              <text class="relation-number">{{ checkParam(userInfo.friends) }}</text>
              <text class="relation-item">&nbsp;朋友</text>
            </view>&nbsp;&nbsp;
            <view>
              <text class="relation-number">{{ checkParam(userInfo.follows) }}</text>
              <text class="relation-item">&nbsp;关注</text>
            </view>&nbsp;&nbsp;
            <view>
              <text class="relation-number">{{ checkParam(userInfo.fans) }}</text>
              <text class="relation-item">&nbsp;粉丝</text>
            </view>
          </view>
          <view class="introduction" v-if="userInfo.introduction !== ''">{{ userInfo.introduction }}</view>
          <view style="color: #9a9a9a;display: flex;align-items: center" v-else>
            点击添加介绍，让大家认识你...
            <u-icon name="edit-pen"></u-icon>
          </view>
          <view class="ip">
            <!--性别年龄-->
            <view v-if="(userInfo?.sex != 3 && userInfo?.sex != null) || userInfo?.birthday !== ''" class="sex">
              <view
                  v-if="(userInfo?.sex != 3 && userInfo?.sex != null) || (userInfo?.sex != 3 && userInfo?.sex !== undefined) "
                  style="display: flex;align-items: center;">
                <image style="margin-right: 5px"
                       :src="userInfo?.sex == 1 ? 'https://www.douluodalu.icu:9000/school/static/man_active.png' : 'https://www.douluodalu.icu:9000/school/static/woman_active.png' ">
                </image>
                <text v-if="userInfo?.sex == 1">男</text>
                <text v-if="userInfo?.sex == 0">女</text>
              </view>
              <text v-if="userInfo?.birthday !== '' && userInfo?.birthday !== this.$NOT_SHOW_BIRTH">
                {{ calculateAge(userInfo?.birthday) }}
              </text>
            </view>

            <!--          地区-->
            <text v-if="oversea != true && userInfo.location?.province != ''">
              {{ userInfo.location?.province }}
            </text>
            <text
                v-if="oversea == true && (userInfo.location?.country != '' && userInfo?.location?.country !== undefined)">
              {{ userInfo.location.country }}
            </text>

            <view
                v-if="(userInfo?.birthday === '' ||  userInfo?.birthday == this.$NOT_SHOW_BIRTH)&& (userInfo?.location?.province === undefined && userInfo?.location?.province === '')"
                class="age">
              <u-icon size="14" name="plus"></u-icon>
              <text>添加年龄、所在地等标签</text>
            </view>
            <view
                v-if="(userInfo?.birthday === '' ||  userInfo?.birthday == this.$NOT_SHOW_BIRTH) && userInfo?.school === ''"
                class="age">
              <u-icon size="14" name="plus"></u-icon>
              <text>添加年龄、学校等标签</text>
            </view>
            <view v-if="userInfo?.school === '' &&
            (userInfo?.birthday !== '' &&  userInfo?.birthday != this.$NOT_SHOW_BIRTH)&&
            (userInfo?.location?.province !== undefined || userInfo?.location?.country.trim() !== '')" class="age">
              <u-icon size="14" name="plus"></u-icon>
              <text>添加学校等标签</text>
            </view>
            <view class="age" v-if="userInfo.school !== ''">
              {{ userInfo.school }}
            </view>

          </view>
        </navigator>
        <view>
          <view class="head-wrapper">
            <u-tabs
                :current="tagIndex"
                @click="toScroll"
                :list="list4"
                lineWidth="20"
                lineHeight="7"
                :lineColor="`url(${lineBg}) 100% 100%`"
                :activeStyle="{
        color: '#303133',
        fontWeight: 'bold',
        transform: 'scale(1.05)'
    }"
                :inactiveStyle="{
        color: '#606266',
        transform: 'scale(1)'
    }"
                itemStyle="padding-left: 5rem; padding-right: 5rem; height: 34px;"
            >
            </u-tabs>
          </view>
          <view class="content-swiper">
            <swiper :current="tagIndex"
                    class="swiper"
                    :circular="false"
                    @change="swiperChange"
                    swiperDuration="250">
              <swiper-item>
                <scroll-view scroll-y style="height: 100vh">
                <BlogForMy @longtap="handleRemove(post,index)" v-for="(post,index) in myPostList"
                           :key="index" :post="post"/>
                <view style="height: 100px;"></view>
                </scroll-view>
              </swiper-item>
              <swiper-item>
                <scroll-view scroll-y style="height: 100vh">
                <BlogForMy @longtap="handleCancelCollection(post,index)" v-for="(post,index) in myCollectionList"
                           :key="index" :post="post"
                />
                <view style="height: 100px;"></view>
                </scroll-view>
              </swiper-item>
            </swiper>
          </view>
        </view>
      </view>
      <!--    未登录-->
      <navigator url="/pages/my/login" v-else class="content">
        <view class="info">
        </view>
        <view>
          <view class="head-wrapper">
            <u-tabs
                :current="tagIndex"
                @click="toScroll"
                :list="list4"
                lineWidth="20"
                lineHeight="7"
                :lineColor="`url(${lineBg}) 100% 100%`"
                :activeStyle="{
        color: '#303133',
        fontWeight: 'bold',
        transform: 'scale(1.05)'
    }"
                :inactiveStyle="{
        color: '#606266',
        transform: 'scale(1)'
    }"
                itemStyle="padding-left: 2rem; padding-right: 2rem; height: 34px;"
            >
            </u-tabs>
          </view>
          <view class="content-swiper">
            <swiper :current="tagIndex"
                    class="swiper"
                    :circular="false"
                    @change="swiperChange"
                    swiperDuration="250">
              <swiper-item>
                <view class="unlogin_content">
                  <image style="margin: 4rem 0 0 2.5rem"
                         src="https://www.douluodalu.icu:9000/school/static/empty.png"></image>
                  <text style="text-align: center">登录解锁更多有趣内容</text>
                </view>
              </swiper-item>
              <swiper-item>
                <view class="unlogin_content">
                  <image style="margin: 4rem 0 0 2.5rem"
                         src="https://www.douluodalu.icu:9000/school/static/empty.png"></image>
                  <text style="text-align: center">登录解锁更多有趣内容</text>
                </view>
              </swiper-item>
              <swiper-item>
                <view class="unlogin_content">
                  <image style="margin: 4rem 0 0 2.5rem"
                         src="https://www.douluodalu.icu:9000/school/static/empty.png"></image>
                  <text style="text-align: center">登录解锁更多有趣内容</text>
                </view>
              </swiper-item>
              <swiper-item>
                <view class="unlogin_content">
                  <image style="margin: 4rem 0 0 2.5rem"
                         src="https://www.douluodalu.icu:9000/school/static/empty.png"></image>
                  <text style="text-align: center">登录解锁更多有趣内容</text>
                </view>
              </swiper-item>

            </swiper>
          </view>
        </view>
      </navigator>
    </scroll-view>
  </view>
  <u-action-sheet cancelText="取消" @close="closeRemoveAction"
                  @select="selectClick"
                  :closeOnClickOverlay="true"
                  :actions="removeActionList"
                  :round="10"
                  :show="showRemove"></u-action-sheet>
  <u-action-sheet cancelText="取消" @close="closeCancelCollectionAction"
                  @select="cancelCollectionClick"
                  :closeOnClickOverlay="true"
                  :actions="cancelCollectionList"
                  :round="10"
                  :show="showCancelCollection"></u-action-sheet>
  <tabbar></tabbar>


</template>

<script>

import {
  getAvatarUrl, getBackgroundUrl,
  getNickName,
  getToken,
  removeAvatarUrl,
  removeExpiresIn,
  removeNickName,
  removeLocation,
  removeToken, removeUserId, getUserId
} from "@/utils/auth";
import {calculateAge} from "@/utils/format";
import Blog from "@/components/Blog.vue";
import {logout} from "@/utils/api";
import tabbar from "@/components/tabbar/tabbar.vue";
import {getFrontUserInfo, getMyCollections, getMyLikeNum, getMyPostList} from "@/api/user";
import BlogForMy from "@/components/BlogForMy.vue";
import user from "@/store/user";
import {downloadTempFile} from "@/utils/downloadFile";
import colorThief from "miniapp-color-thief";
import {removePostById} from "@/api/article";
import {collectPost} from "@/api/post";


export default {
  components: {BlogForMy, Blog, tabbar},

  data() {
    return {
      showRightList: false,
      isLogin: false,
      loading: true,
      nickName: '',
      avatarUrl: '',
      backgroundUrl: '',
      show: false,
      postLoading: true,
      chanelLoading: true,
      collectionLoading: true,
      isPostEmpty: false,
      isChanelEmpty: false,
      isCollectionEmpty: false,
      indexList: [],
      notifyIndex: 0,
      postParams: {
        current: 1,
        pageSize: 15
      },
      chanelParams: {
        current: 1,
        pageSize: 15
      },
      collectionParams: {
        current: 1,
        pageSize: 15
      },
      showRemove: false,
      removeItem:{},
      removeActionList: [{
        name:'删除',
      }],
      showCancelCollection: false,
      cancelCollectionItem:{},
      cancelCollectionList: [{
        name:'取消收藏',
      }],
      myPostList: [],
      myChanelList: [],
      myCollectionList: [],
      myLikeNum: 0,
      tagIndex: 0,
      userId: '',
      lineBg: "",
      list4: [
        {name: '帖子'},
        {name: '收藏'}
      ],
      userInfo: {},
      oversea: null,
      bgHeight: '14rem'
    };
  },
  onShow() {
    let token = getToken();
    const systemInfo = uni.getSystemInfoSync();
    const windowWidth = systemInfo.windowWidth;
    if (token.length > 0) {
      this.isLogin = true
      let userId = getUserId;
      this.userId = userId()
      let nickName = getNickName();
      let avatarUrl = getAvatarUrl();
      this.nickName = nickName
      this.avatarUrl = avatarUrl
      let _this = this;
      Promise.all(
          [this.getUserInfo(this.userId),
            this.getMyPostList(this.userId),
            this.getMyCollectionList(this.userId)
          ]).then(res => {
        setTimeout(() => {
          this.$nextTick(() => {
            this.loading = false
          })
        }, 500)
      })
    }
    uni.$on('alterUserInfo', (res) => {
      // console.log("收到emit:")
      // console.log(res)
      if (res.success == true) {
        setTimeout(() => {
          uni.showToast({
            title: '设置成功',
            icon: 'none'
          })
        }, 1000)
      } else {
        setTimeout(() => {
          uni.showToast({
            title: '设置失败',
            icon: 'none'
          })
        }, 1000)
      }
    })
  },
  onLoad() {
    if (getToken().length == 0) {
      uni.navigateTo({
        url: '/pages/my/login'
      })
    }
  },
  unload() {
    uni.$off('alterLocation')
  },
  methods: {
    handleRemove(item,index){
      let userId = getUserId();
      if (userId !== null && userId !== '' && userId !== undefined && item.authorId == userId) {
        this.showRemove = true
        this.removeItem.item = item
        this.removeItem.index = index
      }

    },
    handleCancelCollection(item,index){
        this.showCancelCollection = true
        this.cancelCollectionItem.item = item
        this.cancelCollectionItem.index = index
    },
    selectClick(index){
      if(index?.name === '删除'){
        let _this = this
        uni.showModal({
          title: '提示',
          content: '内容删除后无法找回，是否确认删除？',
          success: async (res) => {
            if (res.confirm) {
              const res = await removePostById(_this.removeItem.item.id)
              if(res.code == 200){
                uni.showToast({
                  title: '删除成功',
                  icon: 'none'
                })
                _this.myPostList.splice(_this.removeItem.index, 1)
                _this.removeItem = {}
              }else{
                uni.showToast({
                  title: '删除失败',
                  icon: 'none'
                })
              }

              _this.showRemove = false
            } else if (res.cancel) {
              console.log('用户点击取消');
            }
          }
        });
      }
    },
    cancelCollectionClick(index){
      if(index?.name === '取消收藏'){
        let _this = this
        uni.showModal({
          title: '提示',
          content: '确认取消收藏？',
          success: async (res) => {
            if (res.confirm) {
              const res = await collectPost(_this.cancelCollectionItem.item.id)
              if(res.code == 200){
                uni.showToast({
                  title: '已取消收藏',
                  icon: 'none'
                })
                _this.myCollectionList.splice(_this.myCollectionList.index, 1)
                _this.removeItem = {}
              }else{
                uni.showToast({
                  title: '删除失败',
                  icon: 'none'
                })
              }

              _this.showCancelCollection = false
            } else if (res.cancel) {
              console.log('用户点击取消');
            }
          }
        });
      }
    },

    closeRemoveAction(){
      // this.removeItem = {}
      this.showRemove = false
    },
    closeCancelCollectionAction(){
      // this.removeItem = {}
      this.showCancelCollection = false
    },
    checkParam(value) {
      if (value === '' || value === undefined || value === null || value < 0) {
        if (typeof value === 'number') {
          return 0;
        }
        if (typeof value === 'string') {
          return '无';
        }
      } else {
        return value;
      }
    },

    async bgcDownload(file) {
      let bgcUrl = wx.getStorageSync('bgcUrl')
      let result = await downloadTempFile(file, bgcUrl)
    },
    toAlterBackgroud(url) {
      uni.navigateTo({
        url: `/pages/my/alterBackGround?url=${url}&ownerId=${this.userId}`
      })
    },
    toAlterAvatar(url) {
      uni.navigateTo({
        url: `/pages/my/alterAvatar?url=${url}&ownerId=${this.userId}`
      })
    },
    user,
    calculateAge,
    async getUserInfo(id) {
      const res = await getFrontUserInfo(id)
      if (res.code == 200) {
        this.userInfo.username = res.data?.username === undefined ? '' : res.data.username
        this.userInfo.birthday = (res.data?.birthday === undefined || res.data?.birthday == this.$NOT_SHOW_BIRTH) ? '' : res.data.birthday
        this.userInfo.location = res.data.location
        this.oversea = res.data?.oversea
        this.userInfo.sex = res.data?.sex === undefined ? '' : res.data.sex
        this.userInfo.introduction = res.data?.introduction === undefined ? '' : res.data.introduction
        this.userInfo.avatar = res.data?.avatar
        this.userInfo.fans = res.data?.fans
        this.userInfo.follows = res.data?.follows
        this.userInfo.friends = res.data?.friends
        this.userInfo.likes = res.data?.likes

        this.userInfo.school = res.data?.school === undefined ? '' : res.data.school
        this.userInfo.backgroundUrl = res.data?.backgroundUrl === undefined ? this.$DEFAULT_BG : res.data.backgroundUrl
        // this.userInfo. = res.data
      }
      // console.log(this.userInfo)
    },
    async getMyPostList(id) {
      const res = await getMyPostList(id, this.postParams.current, this.postParams.pageSize)
      if (res.code == 200) {
        this.isPostEmpty = res.data?.records?.length == 0
        if (!this.isPostEmpty) {
          this.myPostList = res.data.records.reverse()
        }
        this.postLoading = false
      }
    },
    async getMyChanelList() {
    },
    async getMyCollectionList(id) {
      const res = await getMyCollections(id, this.collectionParams.current, this.collectionParams.pageSize)
      if (res.code == 200) {
        this.isCollectionEmpty = res.data?.records?.length == 0
        if (!this.isCollectionEmpty) {
          this.myCollectionList = res.data.records.reverse()
        }
        this.collectionLoading = false
      }
    },
    async getMyLikeNum(id) {
      const res = await getMyLikeNum(id)
      if (res.code == 200) {
        this.myLikeNum = res.data
      }
    },
    logout() {
      uni.showModal({
        title: '确定退出登录?',
        cancelText: '取消',
        confirmText: '确定',
        confirmColor: '#4ea4f9',
        success(res) {
          if (res.confirm) {
            logout().then(res => {
              console.log(res)
              if (res.code == 200) {
                uni.clearStorageSync()
                setTimeout(() => {
                  uni.reLaunch({
                    url: '/pages/my/my'
                  });
                }, 200)
              }
            })
          } else if (res.cancel) {

          }
        }
      })

    },
    ShowRightList() {
      this.showRightList = true
    },
    open() {
      // console.log('open');
    },
    close() {
      this.showRightList = false
      // console.log('close');
    },
    toLogin() {
      uni.navigateTo({
        url: '/pages/my/login'
      })
    },
    toScroll(event) {
      this.tagIndex = event.index
    },
    swiperChange(event) {
      this.tagIndex = event.detail.current
    },
  }
}
</script>

<style scoped>
.container {
  background: no-repeat center center;
  background-size: cover;
}

.container_unlogin {
  display: flex;
  align-items: center;
  justify-content: center;
}

.userinfo {
  padding: 0 1rem;
  display: flex;
  align-items: center;

//justify-content: start; color: white; height: 12rem;
}

.userinfo_unlogin {
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 0;
  margin: 0;
  background: #56CCF2; /* fallback for old browsers */
  background: -webkit-linear-gradient(to right, #2F80ED, #56CCF2); /* Chrome 10-25, Safari 5.1-6 */
  background: linear-gradient(to right, #2F80ED, #56CCF2); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */

}

.unlogin_text {
  padding: 10px 20px;
  font-size: 18px;
  font-weight: initial;
  color: #fff;
  border-radius: 72rpx;
  background-color: #4ea4f9
}

.avatar image {
  border: 2px solid white;
  width: 5rem;
  height: 5rem;
  border-radius: 50%;
}

.top-right-list {
  background-color: rgba(129, 131, 128, 0.4);
  padding: 3px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  height: 28px;
  width: 28px;
  color: white;
  font-size: 25px;
  text-align: center;
  position: absolute;
  right: 110px;
  top: 48px;
}

.list-wrapper {
  height: calc(91vh - env(safe-area-inset-bottom));
  padding: 10px 15px 15px 15px;
  display: flex;
  flex-direction: column-reverse;
}

.list-item-out {
  border: 1px solid rgba(0, 0, 0, 0.68);
  border-radius: 2px;
  padding: 10px 30px;
  display: flex;
  align-items: center;
  color: black;
}

.name text {
  font-weight: 530;
  font-size: 38rpx;
  margin-left: 20rpx;
}

.content {
  background-color: white;
  margin-top: -25px;
  border-top: 1px solid black;
  border-top-left-radius: 25px;
  border-top-right-radius: 25px;
  padding: 0.8rem 1rem 0 1rem;
}

.relation {
  display: flex;
  align-items: center;;
}

.relation-item {
  color: #999;
  font-size: 24rpx;
}

.relation-number {
  color: #000;
  font-size: 24rpx;
  font-weight: bold;
}

.introduction {
  font-size: 24rpx;
}

.age {
  display: flex;
  align-items: center;
  border-radius: 3px;
  margin-left: 5px;
  color: rgba(84, 87, 87, 0.85);
  background-color: rgba(223, 223, 223, 0.7);
  padding: 3px;
}

.sex {
  display: flex;
  align-items: center;
  border-radius: 3px;
  margin-right: 5px;
  color: rgba(84, 87, 87, 0.85);
  background-color: rgba(223, 223, 223, 0.7);
  padding: 1px;
}

.sex image {
  width: 14px;
  height: 14px;
  padding-left: 4px;
}

.ip text {
  color: rgba(84, 87, 87, 0.85);
  background-color: rgba(223, 223, 223, 0.7);
  border-radius: 3px;
  padding: 3px;
}

.ip {
  display: flex;
  align-items: center;
  margin-top: 0.3rem;
  font-size: 24rpx;
  flex-wrap: wrap;

}

.head-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.head-topic {
  padding-top: 5px;
  width: 25px;
  height: 25px;
}

.search {
  padding-top: 5px;
  padding-right: 5px;
  width: 20px;
  height: 20px;
}


.title {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60rpx;
}

.swiper {
  height: calc(100vh - 120rpx);
}

.unlogin_content {
  display: flex;
  justify-content: center;
  flex-direction: column;
  font-size: 14px;
  color: #b0b0b0;
}

.wrap_content {
  border-radius: 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background: gray;
  height: 100vh;
  color: aqua;
  font-size: 80px;
  margin: 0rpx 40rpx;
}
</style>
